package top.ltc_cn.minecraft_manager.config.Security;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import top.ltc_cn.minecraft_manager.properties.CorsConfigProperties;
import top.ltc_cn.minecraft_manager.properties.InterceptorConfigProperties;

/**
 * Copyright (c) 2024 Xiaoyangcc. All rights reserved.
 * <p>
 * This file is part of the ltc-cn-springboot project.
 * <p>
 * ltc-cn-springboot is distributed under the terms of the MIT License.
 * For details, see the accompanying LICENSE file or visit:
 * <a href="https://www.ltc-cn.top/project/ltc-cn-springboot">...</a>
 */

@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {

//    @Bean
//    public LocaleChangeInterceptor localeChangeInterceptor() {
//        return new LocaleChangeInterceptor();
//    }

    @Value("${spring.profiles.active}")
    private String activeProfile;

    @Resource
    private CorsConfigProperties corsConfigProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        try {
            log.info("Active profile: {} | 当前环境: {}", activeProfile, activeProfile);
            log.info("CORS 配置: {}", corsConfigProperties);

            if (!corsConfigProperties.isEnable()) {
                log.info("CORS 配置为 false，不添加 CORS 配置。");
                return;
            }

            if ("dev".equals(activeProfile)) {
                log.info("Adding CORS mappings... | 添加 CORS 中··· (开发环境) (无添加项目)");
                registry.addMapping("/**")
                        .allowedMethods(corsConfigProperties.getAllowedMethods())
                        .allowedOrigins(corsConfigProperties.getAllowedOrigins())
                        .allowedHeaders(corsConfigProperties.getAllowedHeaders())
                        .allowCredentials(corsConfigProperties.isAllowCredentials())
                        .maxAge(corsConfigProperties.getMaxAge());
            }

            if ("prod".equals(activeProfile)) {
                log.info("Adding CORS mappings... | 添加 CORS 中··· (生产环境)");

                registry.addMapping("/**") // 匹配所有路径
                        .allowedMethods(corsConfigProperties.getAllowedMethods())
                        .allowedOrigins(corsConfigProperties.getAllowedOrigins())
                        .allowedHeaders(corsConfigProperties.getAllowedHeaders())
                        .allowCredentials(corsConfigProperties.isAllowCredentials())
                        .maxAge(corsConfigProperties.getMaxAge());
            }

            log.info("CORS 配置添加完成。");

        } catch (Exception e) {
            log.error("Error adding CORS mappings: ", e);
        }
    }
}
